package com.iflytek.iot.zookeeper.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yu 2019/7/9.
 */
@Configuration
@ConditionalOnMissingBean(CuratorFramework.class)
@EnableConfigurationProperties(ZookeeperProperties.class)
public class ZookeeperAutoConfiguration {

    private final ZookeeperProperties zookeeperProperties;

    public ZookeeperAutoConfiguration(ZookeeperProperties zookeeperProperties) {
        this.zookeeperProperties = zookeeperProperties;
    }

    @Bean(initMethod = "start")
    public CuratorFramework curatorFramework() {
        return CuratorFrameworkFactory.newClient(
                zookeeperProperties.getConnectAddress(),
                zookeeperProperties.getSessionTimeout(),
                zookeeperProperties.getConnectionTimeout(),
                new RetryNTimes(zookeeperProperties.getMaxRetries(), zookeeperProperties.getElapsedTime()));
    }
}
